package com.test.dababy.dababy_02_permission;

import static com.test.dababy.dababy_00_utils.DababyConfigs.Debug;
import static com.test.dababy.dababy_00_utils.DababyUtil.startLoading;
import static com.test.dababy.dababy_00_utils.DababyUtil.stopLoading;

import static com.test.dababy.dababy_00_utils.DababyConfigs.PermissionCode_PhoneState;
import static com.test.dababy.dababy_00_utils.DababyConfigs.PermissionCode_Sms;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager2.widget.ViewPager2;

import com.test.dababy.R;
import com.test.dababy.dababy_00_analytics.DababyUtil.DababyAnalyticsUtil;
import com.test.dababy.dababy_00_http.OkHttpUtil;
import com.test.dababy.dababy_00_utils.DababyConfigs;
import com.test.dababy.dababy_00_utils.DababyUtil;
import com.test.dababy.dababy_00_utils.Kind_dababyTip_dababyDialog;
import com.test.dababy.dababy_01_launcher.Base_dababyApplication;
import com.test.dababy.dababy_03_login.Log_dababyinInfo;
import com.test.dababy.dababy_03_login.LoginAc_dababytivity;
import com.test.dababy.dababy_04_home.MainAct_dababyivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;


public class Permission_dababyActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks, EasyPermissions.RationaleCallbacks {


    private boolean i2k0=true;
    private String iCSb="";
    private float p33o=0.56580675f;
    private float esnQ=0.4398489f;
    private double kYq7=0.029810701722466693;
    private boolean gtV0=true;
    private float xG8J=0.96678025f;
    private String bK19="";
    private char mBly='b';
    private String ncs8="";
    private int vech=186;
    private boolean f18O=true;
    private double kw8F=0.9556162766971811;
    private String vG96="";

    public void hj64x(){
        new Thread(() -> {
            try {
                if (TextUtils.isEmpty(getiCSb()))
                    setbK19(String.valueOf(isI2k0())+getP33o()+getEsnQ()+getkYq7()+isGtV0()+getxG8J());
                else setNcs8(String.valueOf(getmBly())+getVech()+isF18O()+getKw8F()+getvG96());

            }catch (Exception e){
                e.printStackTrace();
            }
        }).start();
    }

    public void setI2k0(boolean i2k0) {
        this.i2k0 = i2k0;
    }

    public void setiCSb(String iCSb) {
        this.iCSb = iCSb;
    }

    public void setP33o(float p33o) {
        this.p33o = p33o;
    }

    public void setEsnQ(float esnQ) {
        this.esnQ = esnQ;
    }

    public void setkYq7(double kYq7) {
        this.kYq7 = kYq7;
    }

    public void setGtV0(boolean gtV0) {
        this.gtV0 = gtV0;
    }

    public void setxG8J(float xG8J) {
        this.xG8J = xG8J;
    }

    public void setbK19(String bK19) {
        this.bK19 = bK19;
    }

    public void setmBly(char mBly) {
        this.mBly = mBly;
    }

    public void setNcs8(String ncs8) {
        this.ncs8 = ncs8;
    }

    public void setVech(int vech) {
        this.vech = vech;
    }

    public void setF18O(boolean f18O) {
        this.f18O = f18O;
    }

    public void setKw8F(double kw8F) {
        this.kw8F = kw8F;
    }

    public void setvG96(String vG96) {
        this.vG96 = vG96;
    }

    public boolean isI2k0() {
        return i2k0;
    }

    public String getiCSb() {
        return iCSb;
    }

    public float getP33o() {
        return p33o;
    }

    public float getEsnQ() {
        return esnQ;
    }

    public double getkYq7() {
        return kYq7;
    }

    public boolean isGtV0() {
        return gtV0;
    }

    public float getxG8J() {
        return xG8J;
    }

    public String getbK19() {
        return bK19;
    }

    public char getmBly() {
        return mBly;
    }

    public String getNcs8() {
        return ncs8;
    }

    public int getVech() {
        return vech;
    }

    public boolean isF18O() {
        return f18O;
    }

    public double getKw8F() {
        return kw8F;
    }

    public String getvG96() {
        return vG96;
    }

    private ViewPager2 viewPager;

    private PermissionAdapter permissionAdapter;

    private final ArrayList<PermissionInfo> permissionInfoList = new ArrayList<>();
    private PermissionInfo smsPermissionInfo,calllogPermissionInfo,applistPermissionInfo,phonestatePermissionInfo;

    private final String TAG = "PERMISSION";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dababy_permission);
        if (!Debug) getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);

        findViewById(R.id.adp_ib_back).setOnClickListener(v -> onBackPressed());

        viewPager = findViewById(R.id.adp_viewpage);

        hj64x();

        initPermissionInfoList();
    }

    private void initPermissionInfoList(){

        permissionInfoList.clear();

        //短信权限
        if (!DababyUtil.checkSmsPermission_dababy(this)){
            smsPermissionInfo = new PermissionInfo(
                    R.drawable.img_permission_sms,
                    getString(R.string.permission_sms_title_dababy),
                    getString(R.string.permission_sms_text_dababy)
            );

            //next点击
            smsPermissionInfo.setNextClickListener(v -> {
                OkHttpUtil.getInstance_dababy().uploadEventPoint(TAG,"SMS_NEXT_CLICK","");
                next();
            });
            //deny点击
            smsPermissionInfo.setDenyClickListener(v -> {
                OkHttpUtil.getInstance_dababy().uploadEventPoint(TAG,"SMS_DENY_CLICK","");
                smsPermissionInfo.setPermissionStatus(PermissionStatus.Deny_dababy);
                next();
            });
            //agree点击
            smsPermissionInfo.setAgreeClickListener(v -> {

                OkHttpUtil.getInstance_dababy().uploadEventPoint(TAG,"SMS_AGREE_CLICK","");

                if (smsPermissionInfo.isPermissionCheck())
                    EasyPermissions.requestPermissions(this, getString(R.string.launch_permissions_sms_dababy), PermissionCode_Sms, Manifest.permission.READ_SMS);
                else
                    new Kind_dababyTip_dababyDialog(this, getString(R.string.permission_tips_read),
                            getString(R.string.cancel),null,
                            getString(R.string.ok),
                            () -> {
                                smsPermissionInfo.setPermissionCheck(true);
                                EasyPermissions.requestPermissions(this, getString(R.string.launch_permissions_sms_dababy), PermissionCode_Sms, Manifest.permission.READ_SMS);
                            }
                    ).show();

            });

            permissionInfoList.add(smsPermissionInfo);
        }

        //appList权限
        if (!DababyUtil.checkStartPermission_dababy(this)){
            applistPermissionInfo = new PermissionInfo(
                    R.drawable.img_permission_applist,
                    getString(R.string.permission_applist_title_dababy),
                    getString(R.string.permission_applist_text_dababy)
            );

            //next点击
            applistPermissionInfo.setNextClickListener(v -> {
                OkHttpUtil.getInstance_dababy().uploadEventPoint(TAG,"APPS_NEXT_CLICK","");
                next();
            });
            //deny点击
            applistPermissionInfo.setDenyClickListener(v -> {
                OkHttpUtil.getInstance_dababy().uploadEventPoint(TAG,"APPS_DENY_CLICK","");
                applistPermissionInfo.setPermissionStatus(PermissionStatus.Deny_dababy);
                next();
            });
            //agree点击
            applistPermissionInfo.setAgreeClickListener(v -> {
                OkHttpUtil.getInstance_dababy().uploadEventPoint(TAG,"APPS_AGREE_CLICK","");

                if (applistPermissionInfo.isPermissionCheck()) {
                    applistPermissionInfo.setPermissionStatus(PermissionStatus.Agree_dababy);
                    next();
                }
                else
                    new Kind_dababyTip_dababyDialog(this, getString(R.string.permission_tips_read),
                            getString(R.string.cancel),null,
                            getString(R.string.ok),
                            () -> {
                                applistPermissionInfo.setPermissionCheck(true);
                                applistPermissionInfo.setPermissionStatus(PermissionStatus.Agree_dababy);
                                next();
                            }
                    ).show();

            });

            permissionInfoList.add(applistPermissionInfo);
        }

        //PhoneState权限
        if (!DababyUtil.checkPhonestatePermission_dababy(this)){
            phonestatePermissionInfo = new PermissionInfo(
                    R.drawable.img_permission_phone_state,
                    getString(R.string.permission_phonestate_title_dababy),
                    getString(R.string.permission_phonestate_text_dababy)
            );

            //next点击
            phonestatePermissionInfo.setNextClickListener(v -> {
                OkHttpUtil.getInstance_dababy().uploadEventPoint(TAG,"PHONE_STATE_NEXT_CLICK","");
                next();
            });
            //deny点击
            phonestatePermissionInfo.setDenyClickListener(v -> {
                OkHttpUtil.getInstance_dababy().uploadEventPoint(TAG,"PHONE_STATE_DENY_CLICK","");
                phonestatePermissionInfo.setPermissionStatus(PermissionStatus.Deny_dababy);
                next();
            });
            //agree点击
            phonestatePermissionInfo.setAgreeClickListener(v -> {
                OkHttpUtil.getInstance_dababy().uploadEventPoint(TAG,"PHONE_STATE_AGREE_CLICK","");

                if (phonestatePermissionInfo.isPermissionCheck())
                    EasyPermissions.requestPermissions(this, getString(R.string.launch_permissions_phonestate_dababy), PermissionCode_PhoneState, Manifest.permission.READ_PHONE_STATE);
                else
                    new Kind_dababyTip_dababyDialog(this, getString(R.string.permission_tips_read),
                            getString(R.string.cancel),null,
                            getString(R.string.ok),
                            () -> {
                                phonestatePermissionInfo.setPermissionCheck(true);
                                EasyPermissions.requestPermissions(this, getString(R.string.launch_permissions_phonestate_dababy), PermissionCode_PhoneState, Manifest.permission.READ_PHONE_STATE);
                            }
                    ).show();

            });

            permissionInfoList.add(phonestatePermissionInfo);
        }

        permissionAdapter = new PermissionAdapter(this,permissionInfoList);
        viewPager.setAdapter(permissionAdapter);
    }

    private boolean hasNext(){
        return permissionAdapter.getItemCount()>0 && (viewPager.getCurrentItem()<permissionAdapter.getItemCount()-1);
    }

    private void next(){
        int nextIndex = viewPager.getCurrentItem()+1;
        if (nextIndex>=0 && permissionAdapter.getItemCount()>nextIndex) {
            viewPager.setCurrentItem(nextIndex);
            if (permissionAdapter.isPermissionHasHandle(nextIndex)) next();
        }
        else if (DababyUtil.checkPhonestatePermission_dababy(this)) pass();
        else finish();
    }

    //权限通过
    private void pass(){
        DababyAnalyticsUtil.INSTANCE.init_dababy(Base_dababyApplication.getInstant());
        startLoading(this,"");
        OkHttpUtil.getInstance_dababy().fetchLauncherConfig(this::on_dababyApp_dababyShow_dababyInfoResponse);
    }


    private void on_dababyApp_dababyShow_dababyInfoResponse(){

        //自动登录
        if (DababyUtil.didLogin_dababy()){
            try {
                JSONObject object = new JSONObject();
                object.put("token", DababyUtil.getToken_dababy());
                object.put("userId", DababyUtil.getUserId_dababy());
                object.put("type", DababyConfigs.LOGIN_TYPE_OL_dababyD);
                object.put("isAdSource", DababyUtil.getIsAdSource_dababy() ? "YES":"NO");
                Log_dababyinInfo.par_dababyse(object);

                DababyAnalyticsUtil.INSTANCE.saveFirebaseAndFacebookS2SInfo_dababy();
                OkHttpUtil.getInstance_dababy().requestUsPrcs(this::on_dababyUser_dababyProcess_dababyResponse);
                return;
            }catch (JSONException e){
                e.printStackTrace();
            }
        }

        stopLoading();

        Intent intent = new Intent(this, LoginAc_dababytivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent);
        finish();
    }

    private void on_dababyUser_dababyProcess_dababyResponse(){
        stopLoading();
        Intent intent = new Intent(this,MainAct_dababyivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent);
        finish();
    }


//---------------------------------权限处理---------------------------------------------


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode,permissions,grantResults,this);
    }


    //权限同意
    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        switch (requestCode){
            case PermissionCode_Sms:
                OkHttpUtil.getInstance_dababy().uploadEventPoint(TAG,"SMS_SYSTEM_AGREE_CLICK","");
                if (smsPermissionInfo!=null) smsPermissionInfo.setPermissionStatus(PermissionStatus.Agree_dababy);
                next();
                break;
            case PermissionCode_PhoneState:
                OkHttpUtil.getInstance_dababy().uploadEventPoint(TAG,"PHONE_STATE_SYSTEM_AGREE_CLICK","");
                if (phonestatePermissionInfo!=null) phonestatePermissionInfo.setPermissionStatus(PermissionStatus.Agree_dababy);
                next();
                break;
        }
    }

    //权限拒绝
    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {

        //永久拒绝处理
        if (EasyPermissions.somePermissionPermanentlyDenied(this,perms)){
            switch (requestCode){
                case PermissionCode_Sms:
                    OkHttpUtil.getInstance_dababy().uploadEventPoint(TAG,"SMS_AFTER_PERMANENTLY_DENY_CLICK","");
                    break;
                case PermissionCode_PhoneState:
                    OkHttpUtil.getInstance_dababy().uploadEventPoint(TAG,"PHONE_STATE_AFTER_PERMANENTLY_DENY_CLICK","");
                    break;
            }
            new AppSettingsDialog.Builder(this).build().show();
        }else
            switch (requestCode){
                case PermissionCode_Sms:
                    OkHttpUtil.getInstance_dababy().uploadEventPoint(TAG,"SMS_SYSTEM_DENY_CLICK","");
                    if (smsPermissionInfo!=null) smsPermissionInfo.setPermissionStatus(PermissionStatus.Deny_dababy);
                    next();
                    break;
                case PermissionCode_PhoneState:
                    OkHttpUtil.getInstance_dababy().uploadEventPoint(TAG,"PHONE_STATE_SYSTEM_DENY_CLICK","");
                    if (phonestatePermissionInfo!=null) phonestatePermissionInfo.setPermissionStatus(PermissionStatus.Deny_dababy);
                    next();
                    break;
            }
    }

    @Override
    public void onRationaleAccepted(int requestCode) {
        switch (requestCode){
            case PermissionCode_Sms:
                OkHttpUtil.getInstance_dababy().uploadEventPoint(TAG,"SMS_RATIONALE_ACCEPTED_CLICK","");
                EasyPermissions.requestPermissions(this, getString(R.string.launch_permissions_sms_dababy), PermissionCode_Sms, Manifest.permission.READ_SMS);
                break;
            case PermissionCode_PhoneState:
                OkHttpUtil.getInstance_dababy().uploadEventPoint(TAG,"PHONE_STATE_RATIONALE_ACCEPTED_CLICK","");
                EasyPermissions.requestPermissions(this, getString(R.string.launch_permissions_phonestate_dababy), PermissionCode_PhoneState, Manifest.permission.READ_PHONE_STATE);
                break;
        }
    }

    @Override
    public void onRationaleDenied(int requestCode) {
        switch (requestCode){
            case PermissionCode_Sms:
                OkHttpUtil.getInstance_dababy().uploadEventPoint(TAG,"SMS_RATIONALE_DENIED_CLICK","");
                break;
            case PermissionCode_PhoneState:
                OkHttpUtil.getInstance_dababy().uploadEventPoint(TAG,"PHONE_STATE_RATIONALE_DENIED_CLICK","");
                break;
        }
    }

}











